package com.lingshu.app.config;

import android.app.Activity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2023/12/28 16:44
 * @Description Activity管理
 */
public class ActivityStack {
    private static ActivityStack INSTANCE;
    private Stack<Activity> activityStack;

    private ActivityStack() {
        activityStack = new Stack<Activity>();
    }

    public static ActivityStack getInstance() {
        if (INSTANCE == null) {
            synchronized (ActivityStack.class) {
                if (INSTANCE == null) {
                    INSTANCE = new ActivityStack();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 入栈
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        activityStack.push(activity);
    }

    /**
     * 出栈
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {
        activityStack.remove(activity);
    }

    public void finishAllActivity() {
        Activity activity;
        while (!activityStack.empty()) {
            activity = activityStack.pop();
            if (activity != null) activity.finish();
        }
    }

    public boolean finishActivity(Class<? extends Activity> cls) {
        Activity activity = findActivityByClass(cls);
        if (activity != null && !activity.isFinishing()) {
            activity.finish();
            return true;
        }
        return false;
    }

    public Activity findActivityByClass(Class<? extends Activity> cls) {
        Activity activity = null;
        Iterator<Activity> iterator = activityStack.iterator();
        while (iterator.hasNext()) {
            activity = iterator.next();
            if (activity != null && activity.getClass().getName().equals(cls.getName()) && !activity.isFinishing()) {
                break;
            }
            activity = null;
        }
        return activity;
    }

    public boolean finishToActivity(Class<? extends Activity> cls, boolean isIncludeSelf) {
        List<Activity> list = new ArrayList<>();
        int size = activityStack.size();
        Activity activity = null;
        for (int i = size - 1; i >= 0; i--) {
            activity = activityStack.get(i);
            if (activity.getClass().isAssignableFrom(cls)) {
                for (Activity a : list) {
                    a.finish();
                }
                return true;
            } else if (i == size - 1 && isIncludeSelf) {
                list.add(activity);
            } else if (i != size - 1) {
                list.add(activity);
            }
        }
        return false;
    }
}